package com.kaibo.roomdemo.activity

import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.design.widget.Snackbar
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import com.kaibo.roomdemo.R
import com.kaibo.roomdemo.data.db.entity.UserEntity
import com.kaibo.roomdemo.data.db.RoomDemoDatabase
import com.kaibo.roomdemo.data.db.entity.BookEntity
import com.orhanobut.logger.Logger
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.app_bar_main.*
import kotlinx.android.synthetic.main.content_main.*
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    companion object {
        private const val TAG = "MainActivity"
    }

    private val userDao = RoomDemoDatabase.getUserDao()

    private val bookDao = RoomDemoDatabase.getBookDao()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
        }

        val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
        drawer_layout.addDrawerListener(toggle)
        toggle.syncState()

        nav_view.setNavigationItemSelectedListener(this)

        add_user.setOnClickListener {
            //            Flowable.create(FlowableOnSubscribe<Long> {
//                val userBean = UserEntity()
//                userBean.name = "王开波"
//                userBean.age = 20
//
//                val insertUser = userDao.insertUser(userBean)
//
//                it.onNext(insertUser)
//                it.onComplete()
//
//            }, BackpressureStrategy.BUFFER)
//                    .subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe({
//                        Log.d(TAG, "$it")
//                    })

            Flowable
                    .create(FlowableOnSubscribe<List<Long>> {
                        val userBean = UserEntity(0, "王开波", 20)

                        val userBean2 = UserEntity(0, "王开波2", 21)

                        val userBean3 = UserEntity(0, "王开波3", 22)

                        val insertUser = userDao.insertUsers(userBean, userBean2, userBean3)

                        it.onNext(insertUser)
                        it.onComplete()

                    }, BackpressureStrategy.DROP)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        it.forEach {
                            Logger.d(it)
                        }
                    }
        }

        find_all.setOnClickListener {
            userDao
                    .findUserAll()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        it.forEach {
                            Logger.d(it)
                        }
                    }
        }

        //查询单个`
        find_by_id.setOnClickListener {
            RoomDemoDatabase.getUserDao()
                    .findUserById(20)
                    .flatMap {
                        Logger.d(it)
                        bookDao.findBookByUserId(it.id)
                    }
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Subscriber<BookEntity> {
                        override fun onSubscribe(s: Subscription) {
                            s.request(1)
                        }

                        override fun onNext(t: BookEntity) {
                            Logger.d(it)
                        }

                        override fun onComplete() {
                            Logger.d("完成")
                        }

                        override fun onError(t: Throwable) {
                            Logger.d("出错")
                        }

                    })

//                    .subscribe({
//                        Logger.d(it)
//                    }, {
//                        it.printStackTrace()
//                        Logger.d("出错")
//                    }, {
//                        Logger.d("完成")
//                    })
        }

        //主外键测试
        foreign_key.setOnClickListener {
            Flowable
                    .create(FlowableOnSubscribe<Long> {

                        val userEntity = UserEntity()
                        userEntity.name = "王开波   哈哈"
                        userEntity.age = 18

                        val userId = RoomDemoDatabase.getUserDao().insertUser(userEntity)

                        val bookEntity = BookEntity()
                        bookEntity.bookName = "语文书"
                        bookEntity.bookPage = 359
                        bookEntity.bookPrice = 29.9
                        bookEntity.userId = userId
                        bookEntity.isRead = true

                        val bookId = RoomDemoDatabase.getBookDao().insertBook(bookEntity)

                        it.onNext(bookId)
                        it.onComplete()
                    }, BackpressureStrategy.MISSING)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        Logger.d(it)
                    }, {
                        it.printStackTrace()
                        Logger.d("出错")
                    }, {
                        Logger.d("完成")
                    })
        }
    }

    override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean =
            when (item.itemId) {
                R.id.action_settings -> true
                else -> super.onOptionsItemSelected(item)
            }


    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
        when (item.itemId) {
            R.id.nav_camera -> {
                // Handle the camera action
            }
            R.id.nav_gallery -> {

            }
            R.id.nav_slideshow -> {

            }
            R.id.nav_manage -> {

            }
            R.id.nav_share -> {

            }
            R.id.nav_send -> {

            }
        }

        drawer_layout.closeDrawer(GravityCompat.START)
        return true
    }
}
